﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Contract.Action;
using ZyGames.Framework.Game.Lang;
using ZyGames.Framework.Game.Service;
using System.Linq;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Script;
using ZyGames.Framework.Net;
using ZyGames.Framework.Common.Serialization;
using System.Threading;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 请求牌桌的详细记录
	/// </summary>
	public class Action30036 : BaseAction
	{
		private int tableID;
		private bool result = false;
		private string log = string.Empty;

		private string recordTableStr = string.Empty;
		private string mvpUserStr = string.Empty;
		private int totalHand = 0; //总手数
		private int totalBuy = 0; //总带入
		private string userScoreStr = string.Empty;  //玩家成绩
		private string roomMaster = string.Empty; //房主信息
		public Action30036(HttpGet actionGetter)
			: base((short)ActionType.DZApplyRecordTableDetailData, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableID", ref tableID))  //牌桌的逻辑ID
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			var gameTable = GameTable.Current.GetGameTableData(tableID);
			if (gameTable == null)
			{
				result = false;
				log = "请求服务器数据异常";
				return true;
			}
			var recordTableData = new RecordTable() { TableID = gameTable.TableID, BeginTime = gameTable.StartTime, Profit = 0, RoomMaster = new SimpleUserDataWithTexture() { HeadIcon = gameTable.MasterHeadIcon, NickName = gameTable.MasterNickName, UserId = gameTable.MasterUserId }, SmallBind = gameTable.SmallBind, TableName = gameTable.TableName, TotalTime = gameTable.TableTime, Insurance = gameTable.InsurancerUserID != 0 };
			recordTableStr = Convert.ToBase64String(ProtoBufUtils.Serialize(recordTableData));

			//遍历当前牌桌 所有玩家的记录
			var usersInTable = GameTable.Current.GetUserTableByTableId(tableID);
			if(usersInTable.Count < 1)
			{
				result = false;
				log = "没有查询到玩家的记录";
				return true;
			}
			SharedUserAndTable tempMvp = null;
			foreach(var record in usersInTable)
			{
				if(tempMvp == null)
					tempMvp = record;
				if(record.Profit > tempMvp.Profit)
					tempMvp = record;
				totalBuy += record.TotalBuy;
			}

			if(tempMvp == null)
			{
				result = false;
				log = "服务器数据异常";
				return true;
			}
			//根据ID查询玩家
			var mvpUser = GameTable.Current.GetUser(tempMvp.UserID);
			if(mvpUser == null)
			{
				result = false;
				log = "当前MVP不存在";
				return true;
			}
			var mvp = new SimpleUserDataWithTexture() { UserId = mvpUser.UserId, NickName = mvpUser.NickName, HeadIcon = mvpUser.HeadIconBytes };
			mvpUserStr = Convert.ToBase64String(ProtoBufUtils.Serialize(mvp));

			//查询几手牌
			var allTableCards = GameTable.Current.ShredGameTableCardsByTableID(tableID);
			if(allTableCards.Count < 1)
			{
				result = false;
				log = "服务器计算当前第几手牌异常";
				return true;
			}
			foreach(var h in allTableCards)
			{
				if (h.Hand > totalHand)
					totalHand = h.Hand;
			}


			List<SimpleUserDataTableScoreRecord> allUserRecord = new List<SimpleUserDataTableScoreRecord>();
			//保险底池
			//查找UserTableRecord
			//所有玩家的牌桌记录
			foreach (var record in usersInTable)
			{
				var user = GameTable.Current.GetUser(record.UserID);
				if (user == null)
					continue;
				//SimpleUserData保存的是玩家头像
				allUserRecord.Add(new SimpleUserDataTableScoreRecord() { IsInsurance = record.IsInsurance, Profit = record.Profit, TotalBuy = record.TotalBuy, UserData = new SimpleUserData() { UserId = record.UserID, HeadIcon = user.HeadIconBytes, NickName = user.NickName } });
			}
			//先按照是否是保险人降序排列，然后按照成绩降序排列
			allUserRecord.Sort((i, j) =>
			{
				if (i.IsInsurance.CompareTo(j.IsInsurance) != 0)
					return -i.IsInsurance.CompareTo(j.IsInsurance);
				else if (i.Profit.CompareTo(j.Profit) != 0)
					return -i.Profit.CompareTo(j.Profit);
				else
					return 1;
			}); //根据盈利降序排列
			userScoreStr = Convert.ToBase64String(ProtoBufUtils.Serialize(allUserRecord));

			//房主的信息
			var master = new SimpleUserData() { UserId = gameTable.MasterUserId, NickName = gameTable.MasterNickName, HeadIcon = "" };
			roomMaster = Convert.ToBase64String(ProtoBufUtils.Serialize(master));
			result = true;
			return true;
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this.result);
			this.PushIntoStack(this.log);
			this.PushIntoStack(this.recordTableStr);
			this.PushIntoStack(this.mvpUserStr);
			this.PushIntoStack(this.totalHand);
			this.PushIntoStack(this.totalBuy);

			//下面是所有人的成绩 //总买入  盈亏
			this.PushIntoStack(this.userScoreStr);
			this.PushIntoStack(this.roomMaster);
		}
	}
}
